import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/native_dart_package.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/paging/model/paging_datas.dart';
import 'package:yt_devops/components/paging/model/paging_params.dart';

import 'package:yt_devops/components/paging/page_controller.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/model/device_product_type_model.dart';
import 'package:yt_devops/pages/devices/device_list/device_list_model.dart';
import 'package:yt_devops/pages/site/site_device_manager/site_device_manager_model.dart';
import 'package:yt_devops/pages/site/site_device_manager/widgets/site_divice_tabview.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/services/site/site_services.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/navigate_utils.dart';

import 'widgets/device_manager_table_view.dart';

class SiteDeviceManagerController
    extends PagingController<DeviceListModel, DeviceListState>
    with GetTickerProviderStateMixin {
  // DeviceServices services = Get.find();
  DeviceServices services = Get.put(DeviceServices());
  SiteServices siteServices = Get.put(SiteServices());

  List<dynamic> typeList = [];

  // List <String> tabs = ['全部(0)','发电单元(0)','储能单元(0)','其他单元(0)'];
  List<String> tabs = [];
  List<Widget> tabviewList = [];

  // List <String> tabs = ['全部(0)'];
  TabController? tabController;
  bool isLoad = false;
  int selectedTitleIndex = 0;
  late int siteId;
  bool isFirstLoading = true;
  // List<SiteDeviceSummaryModel> deviceSummaryList =
  //     <SiteDeviceSummaryModel>[].obs;
  var siteName = '';
  @override
  void onInit() {
    if (Get.arguments != null) {
      siteId = Get.arguments['id'];
      siteName = Get.arguments['siteName'].toString();
    }
    tabController = TabController(length: tabs.length, vsync: this);
    Log.d("==== 站点内Tab设备管理模块111 ====");
    super.onInit();
    // getDeviceType();
    loadSiteDeviceSummaryData();
  }

  @override
  void onReady() {}

  @override
  void onClose() {}

  @override
  getState() {
    return DeviceListState();
  }

  Future<void> setSelectedTitleIndex(int index, int subSystemId) async {
    selectedTitleIndex = index;
    // 刷新数据
    pagingState.subSystemId = subSystemId;
    refreshData();
  }

  /// 根据站点获取各个单元的设备统计数
  Future<void> loadSiteDeviceSummaryData() async {
    Configs.httpClient.requestWithLoading(
      () async {
        var params = {'siteIds': siteId};
        var data = await siteServices.getMonitorDeviceTab(params) as List;
        typeList = data;
        if (data.isNotEmpty) {
          tabviewList.clear();
          tabs.clear();
          moveElementToLast(data, 6);
          for (var element in data) {
            if (element['typeId'] != null) {
              tabs.add(
                  '${'${element['typeName'].toString()}(${element['count']}'})');
            } else {
              tabs.add(element['typeName'].toString());
            }
            tabviewList.add(
              SiteDeviceTabview(
                siteId,
                element['typeId'] != null &&
                        element['typeId'].toString().isNotEmpty
                    ? element['typeId'].toString()
                    : '',
              ),
            );
          }
          tabController = TabController(length: tabs.length, vsync: this);
        }
        update();
      },
      showLoading: false,
      onError: (error) {
        refreshController.loadFailed();
        showError(error.message);
        update();
        return true;
      },
    );
  }

// 将特定 typeId 的对象移动到数组的最后面
  void moveElementToLast(List<dynamic> list, int typeId) {
    // 查找指定 typeId 的元素
    final index = list.indexWhere((element) => element['typeId'] == typeId);
    if (index != -1) {
      // 如果找到了，就将其移除
      final element = list.removeAt(index);
      // 并添加到列表的末尾
      list.add(element);
    }
  }

  @override
  Future<PagingDatas<DeviceListModel>?> loadData(
      PagingParams pagingParams) async {
    // if (pagingState.pageIndex == 1) showLoading(toast:ResKey.loading.tr);
    // // 查询站点设备列表
    // pagingState.siteId = siteId;
    // var json = await services.getDevicelist(
    //   {
    //     'current': pagingParams.pageNum,
    //     'pageSize': pagingParams.pageSize,
    //     'siteId': pagingState.siteId ?? '',
    //     'productTypeId': pagingState.productType?.id ?? '',
    //     'connectStatus': pagingState.connectStatus?.value ?? '',
    //     'name': pagingState.name ?? '',
    //     'sn': pagingState.sn ?? '',
    //     'alarmStatus': pagingState.alarmStatus?.value ?? '',
    //     'siteIds': siteId,
    //     'productTypeIds': pagingState.productTypeIds,
    //     'snOrName': pagingState.snOrName,
    //     'subSystemId': pagingState.subSystemId == 0 ? '' : pagingState.subSystemId
    //   },
    //   onError: (p0) {
    //     if (refreshController.isRefresh) {
    //       refreshController.refreshFailed();
    //     } else {
    //       refreshController.loadFailed();
    //     }
    //     dismissLoading();
    //     handleException(p0);
    //     return false;
    //   },
    // );
    // if (!isLoad) {
    //   isLoad = true;
    //   dismissLoading();
    // }
    // dismissLoading();
    // return PagingDatas<DeviceListModel>.fromJson(json);
  }

  // 获取设备类型
  getDeviceType() => Configs.httpClient.requestWithLoading(() async {
        var data = await siteServices.getMonitorDeviceTab({'siteIds': siteId});
        typeList = data;
        // List.of(data)
        // .map((e) => DeviceProductTypeModel.fromJson(e))
        // .toList();
      }, showLoading: false);

  tapDeviceHandler(DeviceListModel device) {
    if (Get.arguments == 1) {
      // 从添加维修任务来
      Get.back(result: device);
    } else {
      Log.d('tapDeviceHandler==');

      NavigateUtils.toDeviceDetail(
        device.deviceId!,
        device.productType!,
        device.name ?? '',
        device.connectStatus!,
        productId: device.productId,
        deviceTree: device,
      );
    }
  }

  showEmsTab() {
    var index = typeList.indexWhere((element) => element['typeId'] == 1);
    if (index > -1) {
      tabController?.animateTo(index);
    }
  }
}
